import Joi from 'joi';
import debugCheck from '@kuiper-helpers/debug-check';

import joiOmit from '../helpers/joiOmit';
import * as validation from '../../common/validation';
import findManyFilter from '../../common/validation/findManyFilter';

export const pagination = {
	tags: ['api', 'sitePortrait'],
	description: '网站画像任务-分页查看',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },

	validate: {
		payload: Joi.object({
			page: Joi.number().default(1).description('当前页'),
			perPage: Joi.number().default(10).description('每页条目数'),
			filter: findManyFilter.sitePortrait.keys({
				targetSearch: Joi.string().description('子域名模糊查询'),
			}),
		}),
	},

	response: {
		schema: Joi.object({
			data: Joi.object({
				SitePortraitPagination: Joi.object({
					count: Joi.number().description('总条数'),
					pageInfo: Joi.object({
						currentPage: Joi.number().description('当前页数'),
						perPage: Joi.number().description('每页条数'),
						pageCount: Joi.number().description('总页数'),
						itemCount: Joi.number().description('总条数'),
						hasNextPage: Joi.boolean().description('是否有下一页'),
						hasPreviousPage: Joi.boolean().description('是否有上一页'),
					}),
					items: Joi.array().items(
						joiOmit(validation.sitePortraitWithId, {
							required: true,
						}).keys({
							user: Joi.object({
								username: Joi.string().description('用户名'),
							}),
							job: Joi.object({
								_id: Joi.string(),
								note: Joi.string(),
							}),
							result: joiOmit(validation.taskWithId, {
								defualt: true,
								required: true,
							}).allow(null),
						})
					),
				}),
			}),
		}).label('Response'),
	},

	handler: {
		injectGraphql: {
			payloadBuilder(request) {
				const {
					payload: { page, perPage, filter },
				} = request;

				return JSON.stringify({
					variables: { page, perPage, filter },
					// #region query
					query: `
						query($page: Int = 1, $perPage: Int = 10, $filter: FilterFindManySitePortraitInput, $sort: SortFindManySitePortraitInput = _ID_DESC) {
							SitePortraitPagination(page: $page, perPage: $perPage, filter: $filter, sort: $sort) {
								count
								pageInfo {
									currentPage
									perPage
									pageCount
									itemCount
									hasNextPage
									hasPreviousPage
								}
								items {
									_id
									triggerType
									taskSettings {
										enable
										alert
										interval
									}
									isChanged
									securityStatus
									uid
									jobId
									job {
										note
										_id
									}
									target
									lastChangeId
									createTime
									updateTime
									nextExecDate
									user {
										username
									}
								}
							}
						}`,
					// #endregion
				});
			},
		},
	},
};

export const historyPagination = {
	tags: ['api', 'history', 'task'],
	description: '网站画像任务列表-分页查看',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },

	validate: {
		payload: Joi.object({
			page: Joi.number().default(1).description('当前页'),
			perPage: Joi.number().default(10).description('每页条目数'),
			filter: findManyFilter.task.append({
				targetSearch: Joi.string().description('正则过滤target'),
				statusIn: Joi.array().items(Joi.string()).description('任务状态'),
				dateRange: Joi.object({
					startTime: Joi.date().description('开始时间。大于等于'),
					endTime: Joi.date().description('结束时间。小于等于'),
				}).description('结束时间段过滤'),
				startTimeGTE: Joi.date().description('开始时间。大于等于'),
				startTimeLTE: Joi.date().description('开始时间。小于等于'),
				endTimeGTE: Joi.date().description('结束时间。大于等于'),
				endTimeLTE: Joi.date().description('结束时间。小于等于'),
			}),
		}),
	},

	response: {
		schema: Joi.object({
			data: Joi.object({
				TaskPagination: Joi.object({
					count: Joi.number().description('总条数'),
					pageInfo: Joi.object({
						currentPage: Joi.number().description('当前页数'),
						perPage: Joi.number().description('每页条数'),
						pageCount: Joi.number().description('总页数'),
						itemCount: Joi.number().description('总条数'),
						hasNextPage: Joi.boolean().description('是否有下一页'),
						hasPreviousPage: Joi.boolean().description('是否有上一页'),
					}),
					items: Joi.array().items(
						validation.taskWithId.keys({
							user: Joi.object({
								username: Joi.string().description('用户名'),
							}),
							job: Joi.object({
								note: Joi.string(),
							}),
						})
					),
				}),
			}),
		}).label('Response'),
	},

	handler: {
		injectGraphql: {
			payloadBuilder(request) {
				const {
					payload: { page, perPage, filter },
				} = request;

				return JSON.stringify({
					variables: {
						page,
						perPage,
						filter,
					},
					// #region query
					query: `
						query($page: Int = 1, $perPage: Int = 10, $filter: FilterFindManyTaskInput, $sort: SortFindManyTaskInput = _ID_DESC) {
							TaskPagination(page: $page, perPage: $perPage, filter: $filter, sort: $sort) {
								count
								pageInfo {
									currentPage
									perPage
									pageCount
									itemCount
									hasNextPage
									hasPreviousPage
								}
								items {
									_id
									sourceIp
									uid
									taskId
									taskIdx
									prevTaskId
									refType
									refId
									isSpecialTask
									domain
									target
									taskType
									securityStatus
									startTime
									endTime
									status
									progress
									exception
									triggerType
									nextExecDate
									isLatestTask
									repeat {
										cron
										tz
										startTime
										endTime
										limit
										every
										count
									}
									result {
										isChanged
									}
									taskSettings {
										enable
										name
										sourceIp
										target
										collect
										alert
										interval
									}
									user {
										username
									}
									job {
										note
									}
								}
							}
						}`,
					// #endregion
				});
			},
		},
	},
};
